import { defineStore } from 'pinia'
import { ref, type DeepReadonly } from 'vue'
import { DictService } from '@/api/sys/dictApi'

// 定义字典项类型
interface DictItem {
  cnLabel: string
  // 可扩展其他字段如 enLabel/value 等
  [key: string]: any
}

// 定义字典存储结构
type DictCache = Record<string, Record<string | number, DictItem>>

export const useDictStore = defineStore(
  'dict',
  () => {
    // 使用更严格的类型声明
    const cacheMapping = ref<DictCache>({})

    /**
     * 设置/更新字典数据
     * @param mappingKey 字典类型键名
     * @param values 字典数据对象
     */
    const setDict = (mappingKey: string, values: Record<string | number, DictItem>) => {
      cacheMapping.value[mappingKey] = values
    }

    /**
     * 移除指定字典缓存
     * @param mappingKey 字典类型键名
     */
    const removeDict = (mappingKey: string) => {
      if (mappingKey in cacheMapping.value) {
        delete cacheMapping.value[mappingKey]
      }
    }

    /**
     * 获取字典项显示值
     * @param mappingKey 字典类型键名
     * @param valueKey 字典项键值
     * @returns 字典项中文标签或占位符
     */
    const getDictMappingValue = (
      mappingKey: string,
      valueKey: string | number
    ): DeepReadonly<string> => {
      const dict = cacheMapping.value[mappingKey]
      return dict?.[valueKey]?.cnLabel ?? '-'
    }

    /**
     * 获取整个字典类型数据 (只读)
     * @param mappingKey 字典类型键名
     * @returns 字典数据对象或空对象
     */
    const getEntireDict = (mappingKey: string): DeepReadonly<Record<string | number, DictItem>> => {
      return cacheMapping.value[mappingKey] || {}
    }

    /**
     * 从远程加载字典数据
     */
    const loadFromRemote = async () => {
      try {
        const mappings = await DictService.getMappings()
        // 保留现有缓存中未被覆盖的部分
        cacheMapping.value = { ...cacheMapping.value, ...mappings }
      } catch (error) {
        console.error('字典加载失败:', error)
        // 可根据需要添加重试机制或错误处理
      }
    }

    /**
     * 清空所有字典缓存
     */
    const clearAllDicts = () => {
      cacheMapping.value = {}
    }

    // 新增selectOptions缓存
    const selectOptionsCache = ref<Record<string, any[]>>({})

    /**
     * 获取selectOptions缓存
     */
    const getSelectOptions = (code: string): any[] => {
      return selectOptionsCache.value[code] || []
    }

    /**
     * 设置selectOptions缓存
     */
    const setSelectOptions = (code: string, options: any[]) => {
      selectOptionsCache.value[code] = options
    }

    return {
      cacheMapping: cacheMapping as DeepReadonly<typeof cacheMapping>,
      setDict,
      getDictMappingValue,
      removeDict,
      loadFromRemote,
      getEntireDict,
      clearAllDicts,
      // 新增
      getSelectOptions,
      setSelectOptions,
      selectOptionsCache
    }
  },
  {
    persist: {
      key: 'dict',
      storage: localStorage
    }
  }
)